<?php

namespace admin\models;

use admin\traits\ModelStatus;
use ijony\helpers\File;
use ijony\helpers\Folder;
use ijony\helpers\Image;
use Yii;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;

/**
 * This is the model class for table "{{%product}}".
 *
 * @property int $id 产品 ID
 * @property int $category_id 分类 ID
 * @property string $title 标题
 * @property string $model 型号
 * @property string $sub_model 子型号
 * @property string $preview 产品图
 * @property string|null $content 内容
 * @property int $status 状态
 */
class Product extends \common\models\Product
{

    use ModelStatus;

    const STATUS_DELETE = 0;
    const STATUS_INACTIVE = 1;
    const STATUS_ACTIVE = 9;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return ArrayHelper::merge(parent::rules(), [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETE]],
        ]);
    }

    /**
     * @param bool $insert
     *
     * @return bool
     */
    public function beforeSave($insert)
    {
        $file = UploadedFile::getInstance($this, 'preview');
        if ($file) {
            $this->preview = File::newFile($file->getExtension());
        }

        return parent::beforeSave($insert);
    }

    /**
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        $file = UploadedFile::getInstance($this, 'preview');
        if ($file) {
            $file->saveAs(Folder::getStatic($this->preview));

            if ($this->getOldAttribute('preview')) {
                File::delFile(Folder::getStatic($this->getOldAttribute('preview')));
            }
        }
    }

    /**
     * @param int $width
     * @param int $height
     *
     * @return mixed|string
     */
    public function getPreview($width = 0, $height = 0)
    {
        return Image::getImg($this->preview, $width, $height);
    }
}
